package main

import (
	"bytes"
	"encoding/json"
	. "esSync/src"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"

	"github.com/go-chi/chi/v5"
	"github.com/go-chi/chi/v5/middleware"

	"strings"
	"time"

	"github.com/aws/aws-sdk-go/aws/credentials"
	Singer "github.com/aws/aws-sdk-go/aws/signer/v4"
)

func main() {
	r := chi.NewRouter()
	r.Use(middleware.Logger)
	r.Get("/", func(w http.ResponseWriter, r *http.Request) {
		w.Write([]byte("sync Elasticsearch from SNS"))
	})
	r.Post("/pull", pull)
	http.ListenAndServe(":8081", r)
}

func pull(w http.ResponseWriter, r *http.Request) {
	// Read body, just for log
	b, err := ioutil.ReadAll(r.Body)
	defer r.Body.Close()
	if err != nil {
		http.Error(w, err.Error(), 500)
		return
	}
	data := string(b)
	fmt.Println(string(data))

	//todo 权限验证 Permission Validation

	sns := SnsRequest{}
	//decode sns request
	err2 := json.Unmarshal(b, &sns)
	if err2 != nil {
		fmt.Println("SNS Json decode error:", err2)
	}
	//decode message
	msg := &Message{}
	err3 := json.Unmarshal([]byte(sns.Message), &msg)
	if err3 != nil {
		fmt.Println("Message Json decode error:", err3)
	}
	fmt.Println("*Message*", msg)
	addToEs(*msg)
}

//send a post request to es
func addToEs(msg Message) {
	domain := "https://search-myes-qq5q77o5tnm63nnfkzh34hnmhe.ap-east-1.es.amazonaws.com" // e.g. https://my-domain.region.es.amazonaws.com
	index := "user"
	endpoint := domain + "/" + index + "/" + "_doc"

	b, _ := json.Marshal(msg)

	req, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(b))
	req.Header.Set("Content-Type", "application/json")
	req.SetBasicAuth("summer", "hg*GJk6UW")
	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	fmt.Println("status", resp.Status)
	fmt.Println("response:", resp.Header)
	body, _ := ioutil.ReadAll(resp.Body)
	fmt.Println("response Body:", string(body))
}

//this way will occur 401 error,so don't use it for now 
//会报401错误，暂不用
func store(w http.ResponseWriter, r *http.Request) {
	fmt.Println("AK:", os.Getenv("AWS_ACCESS_KEY_ID"))
	fmt.Println("SK:", os.Getenv("AWS_SECRET_ACCESS_KEY"))
	// Basic information for the Amazon OpenSearch Service domain
	domain := "https://search-myes-qq5q77o5tnm63nnfkzh34hnmhe.ap-east-1.es.amazonaws.com" // e.g. https://my-domain.region.es.amazonaws.com
	index := "user"
	endpoint := domain + "/" + index + "/" + "_doc"
	region := "ap-east-1" // e.g. us-east-1
	service := "es"

	// Sample JSON document to be included as the request body
	json := `{ "title": "Thor: Ragnarok", "director": "Taika Waititi", "year": "2017" }`
	body := strings.NewReader(json)

	// Get credentials from environment variables and create the Signature Version 4 signer
	credentials := credentials.NewEnvCredentials()

	signer := Singer.NewSigner(credentials)

	// An HTTP client for sending the request
	client := &http.Client{}

	// Form the HTTP request
	req, err := http.NewRequest(http.MethodPost, endpoint, body)
	if err != nil {
		fmt.Print("Form request error:", err)
	}

	// You can probably infer Content-Type programmatically, but here, we just say that it's JSON
	req.Header.Add("Content-Type", "application/json")
	req.SetBasicAuth("summer", "hg*GJk6UW")

	//报401 暂不用
	// Sign the request, send it, and print the response
	signer.Sign(req, body, service, region, time.Now())
	resp, err := client.Do(req)
	if err != nil {
		fmt.Print("send request error:", err)
	}
	fmt.Print(resp.Status + "\n")
}
